/**
 * 
 */
package com.andrewchatham.pony;

import android.content.Context;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.util.Log;

class MediaScannerClient implements
    MediaScannerConnection.MediaScannerConnectionClient {
  private MediaScannerConnection mConn;
  private boolean mDoneAdding;
  private boolean mConnected;
  private int mPending;

  MediaScannerClient(Context context) {
    mDoneAdding = false;
    mConn = new MediaScannerConnection(context, this);
    mConn.connect();
    mConnected = false;
    mPending = 0;
  }

  public synchronized void setDone() {
    mDoneAdding = true;
    notifyAll();
  }

  public synchronized void scan(String path) {
    while (!mConnected)
      try {
        wait();
      } catch (InterruptedException e) {
        Log.e(SyncService.TAG, e.toString());
      }
    mPending++;
    mConn.scanFile(path, null);
  }

  public synchronized void onScanCompleted(String path, Uri uri) {
    Log.d("Scanner", "Scan done " + uri.toString());
    mPending--;
    notifyAll();
  }

  public synchronized void onMediaScannerConnected() {
    mConnected = true;
    notifyAll();
  }

  public synchronized void waitUntilComplete() {
    try {
      while (!mDoneAdding && mPending > 0)
        wait();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    mConn.disconnect();
  }
}